<template>
  <div :class="{ show: show, searchNormals: !layoutSettings }" class="header-search">
    <!-- <i class="iconfont icon-chaxun" @click.stop="click" /> -->
    <svg class="icon" :class="{ normal: !layoutSettings }" aria-hidden="true" @click.stop="click">
      <use :xlink:href="`${layoutSettings ? '#icon-biaoqiankuozhan_sousuo-354' : '#icon-search'}`" />
    </svg>
    <!-- <i v-else class="iconfont icon-search" @click.stop="click"></i> -->
    <el-select ref="headerSearchSelect" v-model="search" :remote-method="querySearch" filterable default-first-option remote placeholder="菜单搜索：支持拼音、名称等" class="header-search-select" @change="change">
      <el-option v-for="item in options" :key="item.path" :value="item" :label="item.title.join(' > ')" />
    </el-select>
  </div>
</template>

<script>
import { constantRoutes } from '@/router'
// fuse is a lightweight fuzzy-search module
// make search results more in line with expectations
import Fuse from 'fuse.js'
import path from 'path'
import pinyin from 'pinyin'
export default {
  name: 'HeaderSearch',
  props: {
    layoutSettings: false
  },
  data() {
    return {
      search: '',
      options: [],
      searchPool: [],
      show: false,
      fuse: undefined
    }
  },
  computed: {
    routes() {
      return this.$store.getters.routeList || constantRoutes
    }
  },
  watch: {
    routes() {
      this.searchPool = this.generateRoutes(this.routes)
    },
    searchPool(list) {
      this.initFuse(list)
    },
    show(value) {
      if (value) {
        document.body.addEventListener('click', this.close)
      } else {
        document.body.removeEventListener('click', this.close)
      }
    }
  },
  mounted() {
    this.searchPool = this.generateRoutes(this.routes)
  },
  methods: {
    click() {
      this.show = !this.show
      if (this.show) {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
      }
    },
    close() {
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
      this.options = []
      this.show = false
    },
    change(val) {
      this.$router.push(val.path)
      this.search = ''
      this.options = []
      this.$nextTick(() => {
        this.show = false
      })
    },
    initFuse(list) {
      this.fuse = new Fuse(list, {
        shouldSort: true,
        threshold: 0.4,
        location: 0,
        distance: 100,
        maxPatternLength: 32,
        minMatchCharLength: 1,
        keys: [
          {
            name: 'title',
            weight: 0.7
          },
          {
            name: 'path',
            weight: 0.3
          },
          {
            name: 'pTitle',
            weight: 0.7
          }
        ]
      })
    },
    // Filter out the routes that can be displayed in the sidebar
    // And generate the internationalized title
    generateRoutes(routes, basePath = '/', prefixTitle = [], pTitle = []) {
      let res = []

      for (const router of routes) {
        // skip hidden router
        if (router.hidden) {
          continue
        }

        const data = {
          path: path.resolve(basePath, router.path),
          title: [...prefixTitle],
          pTitle: [...pTitle]
        }
        if (router.meta && router.meta.title) {
          data.title = [...data.title, router.meta.title]
          data.pTitle = [
            ...data.pTitle,
            pinyin(router.meta.title, {
              style: pinyin.STYLE_NORMAL
            })
              .toString()
              .replace(/,/g, '')
          ]
          if (router.redirect !== 'noRedirect') {
            // only push the routes with title
            // special case: need to exclude parent router without redirect
            res.push(data)
          }
        }

        // recursive child routes
        if (router.children) {
          const tempRoutes = this.generateRoutes(
            router.children,
            data.path,
            data.title,
            data.pTitle
          )
          if (tempRoutes.length >= 1) {
            res = [...res, ...tempRoutes]
          }
        }
      }
      return res
    },
    querySearch(query) {
      if (query !== '') {
        this.options = this.fuse.search(query)
      } else {
        this.options = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;
  position: relative;
  right: 26px;
  .icon {
    position: absolute;
    width: 28px;
    height: 70px;
  }
  .normal {
    width: 20px;
    color: #010101;
  }
  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0 !important;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 5px;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
      border-radius: 10px;
    }
  }

  &.show {
    .header-search-select {
      width: 210px !important;
      margin-left: 40px;
    }
  }
}
.searchNormals {
  right: 20px !important;
  &.show {
    .header-search-select {
      margin-left: 30px;
    }
  }
}
</style>
